package com.ruitu.mall_98_seller.ui.book;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.ruitu.arad.Arad;
import com.ruitu.arad.api.PageModel;
import com.ruitu.arad.base.base_list.BaseRefreshActivity;
import com.ruitu.arad.base.base_list.ListBaseAdapter;
import com.ruitu.arad.base.base_list.SuperViewHolder;
import com.ruitu.arad.support.view.MyPopWindow;
import com.ruitu.arad.support.widget.progress.ProgressLayout;
import com.ruitu.arad.util.SizeUtils;
import com.ruitu.arad.util.ToastUtils;
import com.ruitu.mall_98_seller.R;
import com.ruitu.mall_98_seller.dao.bean.Book;
import com.ruitu.mall_98_seller.dao.bean.OrderFilter;
import com.ruitu.mall_98_seller.mvp.model.BookModel;
import com.ruitu.mall_98_seller.mvp.presenter.BookPresenter;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.Config;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.util.GlideUtil;
import com.ruitu.router_module.util.RcvUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import static com.ruitu.mall_98_seller.mvp.presenter.OrderPresenter.TIME_PATTERN;

// 预订单列表
public class BookListActivity extends BaseRefreshActivity<BookPresenter.BookListP, BookModel.BookListM> {
    private static final long duration = 180;
    private TextView tv_status;// 订单状态
    private ImageView iv_status;// 状态的三角形

    private BookListAdapter adapter;
    private List<Book> bookList = new ArrayList<>();// 预订单列表

    private MyPopWindow popF1;// 弹窗
    private List<OrderFilter> filterList1 = new ArrayList<>();
    private OrderFilter currfilter1;// 当前选择的筛选条件

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_book_list;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tv_status = findViewById(R.id.tv_status);
        iv_status = findViewById(R.id.iv_status);

        setHeadTitle("预订单列表");
        RcvUtils.refreshCompleteDelay(lRecyclerView, null);
        setOnClickListener(tv_status);

        // 生成订单筛选条件数据
        p.genOrderFilter(filterList1);
        // 默认选择第一条数据
        currfilter1 = filterList1.get(0);

        reqData();
        Arad.bus.register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetEvMsg(EventModel ev) {
        if (ev.getEventCode() == 19083051) {// 收到此消息刷新列表
            resetAndReq();
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == tv_status) {// 点击订单状态
            initPopWindow(filterList1, 1);
            popF1.showAsDropDown(tv_status, SizeUtils.dp2px(0), 0);
            iv_status.animate().rotation(180).setDuration(duration).start();
        }
    }

    @Override
    protected void onItemClick(View v, int position) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("book", bookList.get(position));
        startActivity(BookDetailActivity.class, bundle);
    }

    @Override
    protected RecyclerView.Adapter initAdapter() {
        adapter = new BookListAdapter(this);
        return adapter;
    }

    @Override
    protected LRecyclerView findRecyclerView() {
        return findViewById(R.id.rcv_list);
    }

    @Override
    protected void reqFirst() {
        // 下拉刷新,请求第一页的数据
        currfilter1 = filterList1.get(0);
        tv_status.setText("订单状态");
        resetAndReq();
    }

    private int currPage = 1;
    private int totalPage = 1;

    @Override
    protected void reqMore() {
        currPage++;
        if (currPage > totalPage) {
            refreshNoMoreData();
        } else {
            reqData();
        }
    }

    private void reqData() {
        String comId = AppHolder.instance().getUser().getCompany().getId();
        String status = currfilter1.getValue();
        rxList.add(p.reqBookList(comId, 20, currPage, status));
        showProgress();
    }

    @Override
    public void onReqComplete(int code, boolean isOk, Object data) {
        if (code == 1) {// 获取列表
            PageModel<Book> pageModel = (PageModel<Book>) data;
            currPage = pageModel.getCurrentPage();
            totalPage = pageModel.getTotalPage();
            List<Book> newData = pageModel.getDataList();
            bookList.addAll(newData);
            adapter.setDataList(bookList);

            if (isDataEmpty(bookList)) {
                ToastUtils.showShortSafe("没有符合条件的订单");
            }
        }
    }

    // 重置并请求数据
    private void resetAndReq() {
        currPage = 1;
        bookList.clear();
        adapter.setDataList(bookList);
        reqData();
    }

    private View popView;

    private void initPopWindow(final List<OrderFilter> filterList, final int flag) {
        popView = View.inflate(this, R.layout.pop_order_filter, null);

        if (flag == 1) {
            popF1 = new MyPopWindow(popView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            setPopInfo(popF1);

            popF1.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    iv_status.animate().rotation(0).setDuration(duration).start();
                }
            });
        }

        RecyclerView rcv_list = popView.findViewById(R.id.rcv_list);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        rcv_list.setLayoutManager(manager);
        final AreaListAdapter adapter = new AreaListAdapter(this);
        rcv_list.setAdapter(adapter);
        adapter.setDataList(filterList);
        adapter.setOnItemClickListener(new ListBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int pos) {
                // 点击选择筛选条件
                String name = filterList.get(pos).getName();
                if (flag == 1) {// 筛选状态
                    popF1.dismiss();
                    tv_status.setText(name);
                    currfilter1 = filterList.get(pos);
                    resetAndReq();
                }
            }
        });
    }

    private void setPopInfo(MyPopWindow mPop) {
        mPop.setFocusable(true);
//        mPop.setBackgroundDrawable(new ColorDrawable(66000000));
        mPop.setBackgroundDrawable(new ColorDrawable(00000000));
        mPop.setOutsideTouchable(true);
    }

    // 预订单列表的adapter
    private class BookListAdapter extends ListBaseAdapter<Book> {

        public BookListAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_book_list;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            View item_view = holder.getView(R.id.item_view);
            TextView tv_code = holder.getView(R.id.tv_code);// 订单编号
            TextView tv_time = holder.getView(R.id.tv_time);// 订单时间
            TextView tv_type = holder.getView(R.id.tv_type);// 订单类型
            TextView tv_status = holder.getView(R.id.tv_status);// 订单状态
            TextView tv_name = holder.getView(R.id.tv_name);// 商品名称 订单标题
            TextView tv_price = holder.getView(R.id.tv_price);// 订单货商品价格
            TextView tv_express = holder.getView(R.id.tv_express);// 售后审批
            ImageView iv_pro = holder.getView(R.id.iv_pro);// 图片

            final Book o = mDataList.get(position);// 预订单对象

            tv_code.setText("订单编号：" + o.getId());
            tv_time.setText("下单时间：" + (null == o.getCreateTime() ? "1970-01-01 00:00:00" : new SimpleDateFormat(TIME_PATTERN).format(o.getCreateTime())));
            tv_type.setText("预订单");
            tv_status.setText(p.getStatus(o.getStatus()));
            tv_name.setText(o.getGoodName());
            String priceAndNum = "";
            if (TextUtils.equals(o.getStatus(), "2")) {// 审核通过的预订单,有商品单价
                priceAndNum = "共" + o.getGoodsNum() + "件  单价￥" + o.getGoodsPrice();
            } else {
                priceAndNum = "共" + o.getGoodsNum() + "件  未设置单价";
            }
            tv_price.setText(priceAndNum);
            GlideUtil.loadImg(Config.BASE_URL + o.getGoodsUrl(), iv_pro);

            if (TextUtils.equals("0", o.getStatus())) {// 待处理
                tv_express.setVisibility(View.VISIBLE);
                tv_express.setText("预订审批");
            } else if (TextUtils.equals("1", o.getStatus())) {// 多次(修改)提交
                tv_express.setVisibility(View.VISIBLE);
                tv_express.setText("预订审批");
            } else {
                tv_express.setVisibility(View.GONE);
            }

            tv_express.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("book", o);
                    startActivity(BookApproveActivity.class, bundle);
                    overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                }
            });
        }
    }

    @Override
    protected ProgressLayout findProgressLayout() {
        return null;
    }

    // 下拉筛选条件的adapter
    private class AreaListAdapter extends ListBaseAdapter<OrderFilter> {

        public AreaListAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.pop_item_search_list;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            TextView tv_name = holder.getView(R.id.tv_name);
            tv_name.setText(mDataList.get(position).getName());
        }
    }
}
